<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/6
 * Time: 19:53
 * 小程序
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\Weixin;
use app\common\library\Auth;
use app\common\model\BatchOrder;
use app\common\model\MeridConfig;
use app\common\model\RechargeLog;
use app\extra\WXBizDataCrypt;
use think\Cache;
use think\Db;
use think\Exception;
use think\Validate;

class Weixinauth extends Api
{
	
	
	
	public function _initialize()
	{
		parent::_initialize();
		$cacheName = get_cache_name() . 'smallappConfig/';
		$action = $this->request->action();
		if(!in_array($action, ['weixinNotify', 'rechargenotify'])) {
			if (!$config = check_bebug_cahce($cacheName)) {
				if ($this->appId) {
					$where['appid'] = $this->appId;
				}
				
				$config = Db::name('smallappConfig'
				)
					->where($where)
					->find();
				if (!$config) {
					$this->error('没有配置小程序资料');
				}
				Cache::set($cacheName, $config, 500);
			}
			
			$this->smallAppID = $config['appid'];
			$this->smallAppSecret = $config['app_secret'];
			$this->payKey = $config['pay_key'];
			$this->mchId = $config['mchid'];
		}
		
		
	}
	
	protected $noNeedRight = ['*'];
	protected $noNeedLogin = ['weixinnotify', 'getopenid', 'rechargenotify', 'bindphone', 'getconfig'];
	
	//小程序ID
	public $smallAppID = '';
	//小程序的 app secret
	public $smallAppSecret = '';
	//小程序支付密钥
	public $payKey = '';
	//微信支付商户号
	public $mchId = '';
	
	/**
	 * 获取用户openid
	 */
	public function getOpenid()
	{
		header("Access-Control-Allow-Origin: *");
		$data = input('post.');
		
		//获取用户openid
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->smallAppID . '&secret=' . $this->smallAppSecret . '&js_code=' . $data['code'] . '&grant_type=authorization_code';
		
		
		//获取openid和session_key
		$res = curlGetInfo($url);
		
		if (!$res || isset($res['errcode'])) {
			$this->error('获取数据出错', $res);
		}
		
		$openid = $res['openid'];
		//查看用户是否存在
		$row = Db::name('WeixinInfo')->alias('w')
			->join('user u', 'w.user_id = u.id', 'left')
			->where(['w.openid' => $openid,  'w.type' => 0])
			->lock(true)
			->field('w.user_id, w.id, w.nickname, w.headimgurl as avatar')
			->find();
		
		if ($row && $row['user_id']) {
			//用户存在，登录
			$ret = $this->auth->direct($row['user_id']);
			if ($ret) {
				Db::commit();
				$model = new \app\admin\model\User();
				$userInfo = $model->getRelationInfo($this->auth->id);
				
				$this->success('登录成功', $userInfo);
			} else {
				$this->error('登录出错' . $this->auth->getError());
			}
		} elseif (!$row) {
			$configRow = Db::name('meridConfig')
				->field('reg_need_recommend')
				->find();
			
			if ($configRow && $configRow['reg_need_recommend'] == MeridConfig::NEED_RECOMMEND_Y) {
				if(!isset($data['recommend_id']) || !$data['recommend_id']) {
					$this->error('请通过分享链接注册');
				}
			}
			
			//添加微信信息数据
			$infoData = [
				'openid' => $openid,
				'nickname' => $data['nickName'],
				'sex' => $data['gender'],
				'country' => $data['country'],
				'province' => $data['province'],
				'city' => $data['city'],
				'headimgurl' => $data['avatarUrl'],
				'subscribe_time' => time(),
				'create_time' => time(),
				'update_time' => time(),
				'recommend_user_id' => isset($data['recommend_id']) ? $data['recommend_id'] : '',
			];
			
			$res = Db::name('WeixinInfo')->insertGetId($infoData);
			if (!$res) {
				$this->error('注册出错，请稍候重试');
			}
			$this->success('添加微信信息成功', ['id' => $res]);
		} else {
			$this->success('已有微信信息', ['id' => $row['id']]);
		}
	}
	
	
	/**
	 * 读取/dev/urandom获取随机数,linux下才有用
	 * @return mixed|string
	 */
	function createToken()
	{
		return md5(uniqid(md5(microtime(true)), true));
	}
	
	
	/**
	 * 订单统一下单
	 */
	public function payOrder()
	{
		$orderStrIds = input('post.order_id');
		if (!$orderStrIds) {
			$this->error('订单参数错误');
		}
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$orderIds = explode(',', $orderStrIds);
		$orders = Db::name('order')
			->where(['id' => ['in', $orderIds], 'user_id' => $userId, 'order_status' => $model::STATUS_WAIT_PAYMENT])
			->field('id, order_amount')
			->select();
		if (!$orders) {
			$this->error('没有需要支付的订单');
		}
		
		//合并部份
		$amount = 0;
		foreach ($orders as $order) {
			$amount += $order['order_amount'];
		}
		
		$no = time() . mt_rand(1111, 9999);
		//生成批量支付记录
		$batchData = [
			'no' => $no,
			'order_ids' => $orderStrIds,
			'pay_type' => BatchOrder::TYPE_WEIXIN,
			'create_time' => time(),
			'user_id' => $userId,
			'amount' => $amount
		];
		
		$batchId = Db::name('batchOrder')->insertGetId($batchData);
		if (!$batchId) {
			$this->error('生成支付订单出错');
		}
		
		$user = Db::name('weixinInfo')->where(['user_id' => $userId])->find();
		
		$spbill_create_ip = $_SERVER['REMOTE_ADDR'] == '::1' ? '192.127.1.1' : $_SERVER['REMOTE_ADDR'];
		
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		$notifyUrl = $this->request->domain() . url('api/weixinauth/weixinNotify');
		$data = [
			'appid' => $this->smallAppID, //小程序ID 微信分配的小程序ID
			'mch_id' => $this->mchId, //商户号 微信支付分配的商户号
//			'device_info' => '', //设备号(非必填)
			'nonce_str' => $this->createNoncestr(), //随机字符串 随机字符串，不长于32位
//			'sign_type' => '', //签名类型(非必填)
			'body' => '订单支付', //商品描述
//			'detail' => '', //商品详情(非必填)
			'attach' => 'order', //附加数据(非必填)
			'out_trade_no' => $no, //商户订单号
//			'fee_type' => '', //货币类型(非必填)
			'total_fee' => $amount * 100, //总金额
			'spbill_create_ip' => $spbill_create_ip, //终端IP
//			'time_start' => '', //交易起始时间(非必填)
//			'time_expire' => '', //交易结束时间(非必填)
//			'goods_tag' => '', //商品标记(非必填)
			'notify_url' => $notifyUrl, //通知地址
			'trade_type' => 'JSAPI', //交易类型
//			'limit_pay' => '', //指定支付方式(非必填)
			'openid' => $user['openid'], //用户标识
		];
		
		
		$data['sign'] = $this->getSign($data);
		$xmlData = $this->arrayToXml($data);
		$res = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
		if ($res['return_code'] == 'SUCCESS') {
			$resData = [
				'appId' => $this->smallAppID,
				'timeStamp' => (string)time(),
				'nonceStr' => (string)time(),
				'package' => 'prepay_id=' . $res['prepay_id'],
				'signType' => 'MD5',
			];
			
			Db::name('batchOrder')->where(['id' => $batchId])->update(['prepay_id' => $res['prepay_id']]);
			
			$resData['paySign'] = $this->getSign($resData);
			
			$this->success('生成订单成功', $resData);
		} else {
			$this->error('订单创建出错', $res);
		}
	}
	
	/**
	 * 充值统一下单
	 */
	public function payRechargeOrder()
	{
		$orderStrIds = input('post.order_id');
		if (!$orderStrIds) {
			$this->error('订单参数错误');
		}
		$userId = $this->auth->id;
		
		$model = new \app\common\model\RechargeLog();
		$orderIds = explode(',', $orderStrIds);
		$orders = Db::name('RechargeLog')
			->where(['id' => ['in', $orderIds], 'user_id' => $userId, 'status' => $model::STATUS_W])
			->field('id, pay_amount,order_no')
			->find();
		if (!$orders) {
			$this->error('没有需要支付的订单');
		}
		
		$user = Db::name('weixinInfo')->where(['user_id' => $userId])->find();
		
		$spbill_create_ip = $_SERVER['REMOTE_ADDR'] == '::1' ? '192.127.1.1' : $_SERVER['REMOTE_ADDR'];
		
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		$notifyUrl = $this->request->domain() . url('api/weixinauth/rechargeNotify');
		$data = [
			'appid' => $this->smallAppID, //小程序ID 微信分配的小程序ID
			'mch_id' => $this->mchId, //商户号 微信支付分配的商户号
//			'device_info' => '', //设备号(非必填)
			'nonce_str' => $this->createNoncestr(), //随机字符串 随机字符串，不长于32位
//			'sign_type' => '', //签名类型(非必填)
			'body' => '订单支付', //商品描述
//			'detail' => '', //商品详情(非必填)
			'attach' => 'order', //附加数据(非必填)
			'out_trade_no' => $orders['order_no'], //商户订单号
//			'fee_type' => '', //货币类型(非必填)
			'total_fee' => $orders['pay_amount'] * 100, //总金额
			'spbill_create_ip' => $spbill_create_ip, //终端IP
//			'time_start' => '', //交易起始时间(非必填)
//			'time_expire' => '', //交易结束时间(非必填)
//			'goods_tag' => '', //商品标记(非必填)
			'notify_url' => $notifyUrl, //通知地址
			'trade_type' => 'JSAPI', //交易类型
//			'limit_pay' => '', //指定支付方式(非必填)
			'openid' => $user['openid'], //用户标识
		];
		
		
		$data['sign'] = $this->getSign($data);
		$xmlData = $this->arrayToXml($data);
		$res = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
		if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
			$resData = [
				'appId' => $this->smallAppID,
				'timeStamp' => (string)time(),
				'nonceStr' => (string)time(),
				'package' => 'prepay_id=' . $res['prepay_id'],
				'signType' => 'MD5',
			];
			
			$resData['paySign'] = $this->getSign($resData);
			
			$this->success('生成订单成功', $resData);
		} else {
			$this->error('订单创建出错', $res);
		}
	}
	
	
	private static function postXmlCurl($xml, $url, $second = 30) {
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, false);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		
		
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($ch, CURLOPT_TIMEOUT, 40);
		set_time_limit(0);
		
		
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if ($data) {
			curl_close($ch);
			return $data;
		} else {
			$error = curl_errno($ch);
			curl_close($ch);
			throw new WxPayException("curl出错，错误码:$error");
		}
	}
	
	
	//数组转换成xml
	private function arrayToXml($arr) {
		$xml = "<root>";
		foreach ($arr as $key => $val) {
			if (is_array($val)) {
				$xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
			} else {
				$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
			}
		}
		$xml .= "</root>";
		return $xml;
	}
	
	
	//xml转换成数组
	private function xmlToArray($xml) {
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		
		$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
		
		$val = json_decode(json_encode($xmlstring), true);
		return $val;
	}
	
	
	//作用：产生随机字符串，不长于32位
	private function createNoncestr($length = 32) {
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	
	
	//作用：生成签名
	public function getSign($Obj) {
		foreach ($Obj as $k => $v) {
			if ($v) {
				$Parameters[$k] = $v;
			}
		}
		//签名步骤一：按字典序排序参数
		ksort($Parameters);
		$String = $this->formatBizQueryParaMap($Parameters, false);
		//签名步骤二：在string后加入KEY
		$String = $String . "&key=" . $this->payKey;
		//签名步骤三：MD5加密
		$String = md5($String);
		//签名步骤四：所有字符转为大写
		$result_ = strtoupper($String);
		return $result_;
	}
	
	
	///作用：格式化参数，签名过程需要使用
	private function formatBizQueryParaMap($paraMap, $urlencode) {
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v) {
			if ($urlencode) {
				$v = urlencode($v);
			}
			$buff .= $k . "=" . $v . "&";
		}
		$reqPar = '';
		if (strlen($buff) > 0) {
			$reqPar = substr($buff, 0, strlen($buff) - 1);
		}
		return $reqPar;
	}
	
	/**
	 * 微信异步通知
	 */
	public function weixinNotify(){
		header('Content-type:text/html;charset=utf8');
		$dir = RUNTIME_PATH . 'notify/wechat/';
		
		if (!is_dir($dir)) {
			mkdir($dir, 0755, true);
		}
		$mytext = $dir . date('Y-m-d') . '.txt';
		file_put_contents($mytext, '===================' . date('Y-m-d H:i:s') . "==============\r\n", FILE_APPEND);

//		$xml = $GLOBALS['HTTP_RAW_POST_DATA']; //返回的xml
		$xml = file_get_contents('php://input', 'r');
		//记录日志 支付成功后查看weixin.txt文件是否有内容 如果有xml格式文件说明回调成功
		$xmlObj = simplexml_load_string($xml, 'SimplexmlElement', LIBXML_NOCDATA);
		file_put_contents($mytext, json_encode($xmlObj) . "\r\n", FILE_APPEND);
		$data = json_decode(json_encode($xmlObj), true);

//              $json = '{"appid":"wxed4247ab54237770","attach":"recharge","bank_type":"ICBC_CREDIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1492925452","nonce_str":"ngcss6t997p2y87xgyqhzpjvyka5hi7p","openid":"oAyki0ZscT9DYCvuM99N0_iALVyM","out_trade_no":"15253572248600","result_code":"SUCCESS","return_code":"SUCCESS","sign":"BB790851BECC4A4554864C58C4D3B818","time_end":"20180503222152","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000132201805031992216302"}';
//
//              $data = json_decode($json, true);
		$data_sign = $data['sign'];
		// sign不参与签名算法
		unset($data['sign']);
		$pay_no = $data['out_trade_no'];
		$batch = Db::name('rechargeLog')->where('no',$pay_no)->find();
		$config = Db::name('smallappConfig'
		)
			->find();
		if (!$config) {
			file_put_contents($mytext, '没有配置小程序资料', FILE_APPEND);
			die;
		}
		
		$this->smallAppID = $config['appid'];
		$this->smallAppSecret = $config['app_secret'];
		$this->payKey = $config['pay_key'];
		$this->mchId = $config['mchid'];
		
		$sign = $this->getSign($data);
		
		// 判断签名是否正确  判断支付状态
		if (($sign !== $data_sign) || ($data['return_code'] != 'SUCCESS') || ($data['result_code'] != 'SUCCESS')) {
//                      echo '验证失败';
			file_put_contents($mytext, '验证失败', FILE_APPEND);
			die;
		}
		$trade_no = $data['transaction_id'];
		$amount = $data['total_fee'] / 100;
		$model = new BatchOrder();
		$res = $model->paySuccess($pay_no, $trade_no, $model::TYPE_WEIXIN, $amount);
		
		if ($res) {
			file_put_contents($mytext, "=========支付成功=========\r\n", FILE_APPEND);


//                      echo '支付成功';
			$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
			echo $xml;
			die;
			
		} else {
			file_put_contents($mytext, $model->getError() . "=======支付出错======", FILE_APPEND);
			die;
		}
		
		
	}
	
	/**
	 * 微信充值异步通知
	 */
	public function rechargeNotify()
	{
		header('Content-type:text/html;charset=utf8');
		$dir = RUNTIME_PATH . 'notify/wechatRecharge/';
		if (!is_dir($dir)) {
			mkdir($dir, 0777, true);
		}
		$mytext = $dir . date('Y-m-d') . '.txt';
		file_put_contents($mytext, '===================' . date('Y-m-d H:i:s') . "==============\r\n", FILE_APPEND);

//		$xml = $GLOBALS['HTTP_RAW_POST_DATA']; //返回的xml
		$xml = file_get_contents('php://input', 'r');
		//记录日志 支付成功后查看weixin.txt文件是否有内容 如果有xml格式文件说明回调成功
		$xmlObj = simplexml_load_string($xml, 'SimplexmlElement', LIBXML_NOCDATA);
		file_put_contents($mytext, json_encode($xmlObj) . "\r\n", FILE_APPEND);
		$data = json_decode(json_encode($xmlObj), true);

//              $json = '{"appid":"wx17bea8f87c357e13","attach":"order","bank_type":"ICBC_CREDIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1311338601","nonce_str":"11j7k1fjagr7fd6n45bne24vkdrpyzg4","openid":"oqQ_r4hsjHjDU2RPTqml6a7lvu0A","out_trade_no":"749941533609972","result_code":"SUCCESS","return_code":"SUCCESS","sign":"4E79F1690B7FB19FF4E990DFD10E6F6F","time_end":"20180807104633","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000175201808075400421499"}';
//
//              $data = json_decode($json, true);
		$data_sign = $data['sign'];
		// sign不参与签名算法
		unset($data['sign']);
		
		
		$pay_no = $data['out_trade_no'];
		$batch = Db::name('rechargeLog')->where('order_no',$pay_no)->find();
		if (!$batch) {
			file_put_contents($mytext, '订单不存在', FILE_APPEND);
			die;
		}
		
		$config = Db::name('smallappConfig'
		)
			->find();
		if (!$config) {
			file_put_contents($mytext, '没有配置小程序资料', FILE_APPEND);
			die;
		}
		
		$this->smallAppID = $config['appid'];
		$this->smallAppSecret = $config['app_secret'];
		$this->payKey = $config['pay_key'];
		$this->mchId = $config['mchid'];

		$sign = $this->getSign($data);
		
		// 判断签名是否正确  判断支付状态
		if (($sign !== $data_sign) || ($data['return_code'] != 'SUCCESS') || ($data['result_code'] != 'SUCCESS')) {
//                      echo '验证失败';
			file_put_contents($mytext, '验证失败', FILE_APPEND);
			die;
		}
		$trade_no = $data['transaction_id'];
		$amount = $data['total_fee'] / 100;
		$model = new RechargeLog();
		$res = $model->paySuccess($pay_no, $amount, $trade_no, $model::TYPE_6);
		
		if ($res) {
			file_put_contents($mytext, "=========支付成功=========\r\n", FILE_APPEND);
//                      echo '支付成功';
			$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
			echo $xml;
			die;
			
		} else {
			file_put_contents($mytext, $model->getError() . "=======支付出错======", FILE_APPEND);
			die;
		}
		
		
	}
	
	/**
	 * 修改手机号
	 * @param string $email 手机号
	 * @param string $captcha 验证码
	 */
	public function bindmobile()
	{
		$user = $this->auth->getUser();
		$mobile = $this->request->request('mobile');
		$captcha = $this->request->request('code');
		if (!$mobile || !$captcha) {
			$this->error(__('Invalid parameters'));
		}
		if (!Validate::regex($mobile, "^1\d{10}$")) {
			$this->error(__('Mobile is incorrect'));
		}
		
		
		$sms = new \app\common\library\Sms();
		$result = $sms::check($mobile, $captcha, 'bindmobile');
		if ($result !== true) {
			$this->error($result);
		}
		
		$row = \app\common\model\User::where('mobile', $mobile)->find();
		if ($row) {
			//已经有用户了，更改绑定的用户
			$weixinInfo = Db::name('weixinInfo')->where(['user_id' => $user->id])->find();
			$weixinRes = Db::name('weixinInfo')->where(['user_id' => $user->id])->update(['user_id' => $row['id']]);
			Db::name('user')->where(['id' => $row['id']])->update([
				'avatar' => $weixinInfo['headimgurl']
			]);
		} else {
			$user->mobile = $mobile;
			$user->save();
		}
		
		Auth::instance()->logout();
		
		$sms::flush($mobile, 'changemobile');
		$this->success();
	}
	
	
	/**
	 * 绑定用户微信绑定的手机号
	 */
	public function bindPhone()
	{
		$iv = input('post.iv');
		$encryptedData = input('post.encryptedData');
		$code = input('post.code');
		
		
		//获取openid和session_key
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->smallAppID . '&secret=' . $this->smallAppSecret . '&js_code=' . $code . '&grant_type=authorization_code';
		$res = curlGetInfo($url);
		
		
		
		if (!$res || isset($res['errcode'])) {
			$this->error('获取数据出错', $res);
		}
		
		$sessionKey = $res['session_key'];
		$pc = new WXBizDataCrypt($this->smallAppID, $sessionKey);
		$data = [];
		//解密数据
		$errCode = $pc->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0) {
			$data = json_decode($data, true);
			
			//解压后的手机号
			$phone = $data['purePhoneNumber'];
			
			//查找该手机号已经有绑定了用户，有直接绑定微信信息后登录，否则是新用户
			$user = Db::name('user')
				->where(['mobile' => $phone])
				->find();
			
			//微信信息ID
			$infoId = input('post.info_id');
			if ($user) {
				//手机号已经绑定了用户，直接绑定微信信息
				$res = Db::name('weixinInfo')
					->where(['id' => $infoId])
					->update(['user_id' => $user['id']]);
				if (!$res) {
					$this->error('绑定微信信息出错');
				}
				
				$userId = $user['id'];
			} else {
				//查找微信信息
				$info = Db::name('weixinInfo')
					->find($infoId);
				$recommendId = '';
				$parent_path = '';
				
				//推荐人相关操做
				if ($info['recommend_user_id']) {
					
					$recommend_id = $info['recommend_user_id'];
					$recommend = Db::name('user')->where([
						'id' => $recommend_id,
						'status' => 1
					])->field('id, parent_path')->find();
					if ($recommend) {
						$recommendId = $recommend['id'];
						
						//生成所有上级路径
						if ($recommend['parent_path']) {
							$parent_path = $recommend['parent_path'] . ',' . $recommend['id'];
						} else {
							$parent_path = $recommend['id'];
						}
					}
				}
				$pararms = [
					'pay_password' => '',
					'recommend_id' => $recommendId,
					'parent_path' => $parent_path,
					'avatar' => $info['headimgurl'],
					'nickname' => $info['nickname'],
					'gender' => $info['sex'],
					'mobile' => $phone
				];
				
				//生成随机用户名
				$username = 'wx_' . time() . mt_rand(1000, 9999);
				//生成密码
				$password = mt_rand(111111, 999999);
				Db::startTrans();
				try {
					//注册用户
					$ret = $this->auth->register($username, $password, '', '', $pararms);
					if (!$ret) {
						throw new Exception($this->auth->getError());
					}
					
					//更改绑定信息
					$res = Db::name('weixinInfo')
						->where(['id' => $infoId])
						->update(['user_id' => $this->auth->id]);
					if (!$res) {
						$this->error('绑定微信信息出错');
					}
					
					$userId = $this->auth->id;
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				
			}
			$ret = $this->auth->direct($userId);
			$model = new \app\admin\model\User();
			$userInfo = $model->getRelationInfo($userId);
			$this->success('绑定微信信息成功', $userInfo);
		} else {
			$data = [
				'iv' => $iv,
				'encryptedData' => $encryptedData,
				'code' => $code,
				'session_key' => $sessionKey,
				'errCode' => $errCode,
			];
			$this->error('绑定手机号出错', $data);
		}
	}
	
	public function getConfig(){
		$config = Db::name('smallappConfig')
			->find();
		$this->success('查询成功', $config);
	}
}
